package com.xiyuan.smartutils.client.ws.core.auth;

import com.xiyuan.smartutils.client.exception.WebSocketException;

import java.util.EnumMap;
import java.util.List;
import java.util.Map;

/**
 * The Class DefaultAuthenticator.
 *
 * @author xiyuan-lgz
 */
public class DefaultAuthenticator extends AbstractAuthenticator
{

    /** The basic authenticator. */
    private BasicAuthenticator basicAuthenticator;

    /** The digest authenticator. */
    private DigestAuthenticator digestAuthenticator;

    /** The spengo authenticator.(Windows only) */
//     private SpengoAuthenticator spengoAuthenticator;

    /**
     * Instantiates a new default authenticator.
     */
    public DefaultAuthenticator()
    {
        this.basicAuthenticator = new BasicAuthenticator();
        this.digestAuthenticator = new DigestAuthenticator();
        // if(System.getProperty("os.name").indexOf("Windows") > -1){
        // this.spengoAuthenticator = new SpengoAuthenticator();
        // }
    }

    /**
     * Instantiates a new default authenticator.
     *
     * @param basicAuthenticator  the basic authenticator
     * @param digestAuthenticator the digest authenticator
     */
    public DefaultAuthenticator(BasicAuthenticator basicAuthenticator, DigestAuthenticator digestAuthenticator)
    {
        this.basicAuthenticator = basicAuthenticator;
        this.digestAuthenticator = digestAuthenticator;
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * jp.a840.websocket.auth.AbstractAuthenticator#getCredentials(java.util.
     * List)
     */
    @Override
    public String getCredentials(List<Challenge> challengeList) throws WebSocketException
    {
        Map<AuthScheme, Challenge> schemeMap = new EnumMap<AuthScheme, Challenge>(AuthScheme.class);
        for (Challenge challenge : challengeList)
        {
            schemeMap.put(challenge.getScheme(), challenge);
        }

        // if(this.spengoAuthenticator != null &&
        // schemeMap.containsKey(AuthScheme.Negotiate)){
        // this.spengoAuthenticator.init(this.websocket, this.credentials);
        // return
        // this.spengoAuthenticator.getCredentials(schemeMap.get(AuthScheme.Negotiate));
        // }else
        if (schemeMap.containsKey(AuthScheme.Digest))
        {
            this.digestAuthenticator.init(this.websocket, this.credentials);
            return this.digestAuthenticator.getCredentials(schemeMap.get(AuthScheme.Digest));
        }
        else if (schemeMap.containsKey(AuthScheme.Basic))
        {
            this.basicAuthenticator.init(this.websocket, this.credentials);
            return this.basicAuthenticator.getCredentials(schemeMap.get(AuthScheme.Basic));
        }
        return null;
    }
}
